'''※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
File Name: LocalService.py
Author: GID5564
Description: 本地服务
Version: 1.0
Created Time: 04/09/23-12:52:48
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※'''
  
#!/usr/bin/python
# -*- coding: UTF-8 -*-

from http.server import SimpleHTTPRequestHandler
from http.server import CGIHTTPRequestHandler
from http.server import ThreadingHTTPServer
from functools import partial
import contextlib
import sys
import os
import android
import re
import datetime
import webbrowser


#验证网址协议
def verify_prefix(url=None):
    if url is None or len(url.strip()) < 7:
        return False
    if not url.startswith('http://') and not url.startswith('https://') and not url.startswith('ftp://'):
        return False
    return True
 
#验证网络地址
def verify_path_loose(url=None):
    if not verify_prefix(url):
        return False
    path = url[url.index('://')+3:]
    try:
        if not path.index('.') > 0 or not path.index('.') < len(path) - 1:
            return False
    except ValueError:
        return False
    return True
    
    
#打开网址
def open_url(url:str):
    #首先尝试使用Android设备上的默认浏览器，若失败则使用Python的webbrowser模块.
    if not verify_prefix(url) :
        url='http://'+url
    try:
        droid = android.Android()
        # 启动默认浏览器
        droid.startActivity("android.intent.action.VIEW", url, None, None, None, None,None)
    except Exception as e:
        webbrowser.open(url)

#网页搜索
def search_content(content):
    droid = android.Android()
    # 启动浏览器,搜索内容
    data={'query':content}
    droid.startActivity("android.intent.action.WEB_SEARCH", None, None,data, None, None,None)
    
# 桌面通知
def notify(msg):
    droid = android.Android()
    droid.makeToast(msg)

# 拔打电话
def dial(number):
    droid = android.Android()
    data=f"tel:{number}"
    droid.phoneDial(data)   
    # 呼叫电话号码10001
    #droid.phoneDialNumber(str(number))

#朗读
def tts(msg):
    droid = android.Android()
    droid.ttsSpeak(msg)
    
    
# 拍照
def take_picture(suffix=".png"):
    droid = android.Android()
    pic_name = "camera_"+datetime.datetime.now().strftime('%Y%m%d%H%M%S')+suffix
    save_path=os.path.join("/sdcard/DCIM/Camera",pic_name)
    droid.cameraCapturePicture(save_path)
 
# 播放音频文件
def play_audio(file_path):
    droid = android.Android()
    droid.mediaPlay(file_path)
 
# 播放视频文件
def play_video(file_path):
    droid = android.Android()
    droid.startActivity("android.intent.action.VIEW", file_path)
    
#录制视频
def record():
    droid = android.Android()
    droid.startInteractiveVideoRecording()

#简单web服务
class DualStackServer(ThreadingHTTPServer):
    def server_bind(self):
        # suppress exception when protocol is IPv4
        with contextlib.suppress(Exception):
            self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
        return super().server_bind()


def run(server_class=DualStackServer,
        handler_class=SimpleHTTPRequestHandler,
        port=8000,
        bind='127.0.0.1',
        cgi=False,
        directory=os.getcwd()):
    """Run an HTTP server on port 8000 (or the port argument).

    Args:
        server_class (_type_, optional): Class of server. Defaults to DualStackServer.
        handler_class (_type_, optional): Class of handler. Defaults to SimpleHTTPRequestHandler.
        port (int, optional): Specify alternate port. Defaults to 8000.
        bind (str, optional): Specify alternate bind address. Defaults to '127.0.0.1'.
        cgi (bool, optional): Run as CGI Server. Defaults to False.
        directory (_type_, optional): Specify alternative directory. Defaults to os.getcwd().
    """

    if cgi:
        handler_class = partial(CGIHTTPRequestHandler, directory=directory)
    else:
        handler_class = partial(SimpleHTTPRequestHandler, directory=directory)

    with server_class((bind, port), handler_class) as httpd:
        print(
            f"Serving HTTP on {bind} port {port} "
            f"(http://{bind}:{port}/) ..."
        )
        try:
            #直接打开网页
            open_url(f"http://{bind}:{port}")
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            sys.exit(0)


def send_sms(url,api_key, phone_number, message):
    """
    发送短信的函数。

    参数：
    url(str):
        设置短信服务提供商的API地址
    api_key (str): 短信服务提供商的API密钥。
    phone_number (str): 接收短信的手机号码。
    message (str): 要发送的短信内容。

    返回：
    dict: 短信发送结果，包含状态码和消息。
    """
    # 导入所需库
    import requests
    # 设置短信服务提供商的API地址
    #url = "https://sms-api.example.com/send"

    # 设置请求头
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    # 设置请求体
    data = {
        "phone_number": phone_number,
        "message": message
    }

    # 发送请求
    response = requests.post(url, json=data, headers=headers)

    # 解析响应
    result = response.json()

    return result


if __name__ == '__main__':
    bind=sys.argv[1]
    port=sys.argv[2]
    run(port=int(port), bind=bind)
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
